package com.zm.util;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.SCPInputStream;
import com.jcraft.jsch.JSchException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by ZM on 2022/2/11 10:04
 */

public class DownloadFileToServerUtil {

    //从指定服务器的指定目录下，下载指定的文件，返回临时文件的绝对路径
    //@Async//加这个注解有时会还因为还在下载数据但是已经返回了空的值
    public  static String downloadFile(Connection connection,String targetPath, String remoteFileName,String tempFileName) throws Exception{
        String tempFilePath = "";
        if (connection==null){
            throw new RuntimeException("连接不存在！");
        }else if(remoteFileName==null || "".equals(remoteFileName.trim())){
            throw new RuntimeException("远程服务器拉取的文件名不能为空!");
        }
            tempFilePath=remoteDownloadFile(targetPath,connection,tempFileName, remoteFileName);
        //拉取成功后返回临时文件所在的绝对路径
        return tempFilePath;
    }


    private static String remoteDownloadFile(String targetPath,Connection connection, String tempFileName,
                                             String remoteFileName) throws IOException {
        ch.ethz.ssh2.Session session = null;
        SCPInputStream scpi = null;
        FileOutputStream fos = null;
        File file=null;
        String[] split = tempFileName.split("\\.");
        if (split.length<2){
            return "";
        }

        try {
            session = connection.openSession();// 打开一个会话

            SCPClient scpClient = connection.createSCPClient();

            scpi = scpClient.get(targetPath+remoteFileName);
            file=File.createTempFile(split[0],"."+split[1]);
            fos = new FileOutputStream(file);

            byte[] buf = new byte[1024];
            int hasMore = scpi.read(buf);
            System.out.println("开始读");
            while(hasMore != -1){
                fos.write(buf);
                hasMore= scpi.read(buf);

            }
            System.out.println("结束读");
        } finally {//关闭流
            if(null != scpi){
                try {
                    scpi.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != fos){
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != session){
                session.close();
            }
            //在调用的外部以释放连接回连接池的方式替代关闭连接
//            if(null != connection){
//                connection.close();
//            }
        }
        return file.getAbsolutePath();
    }



}
